package com.bjpowernode.gateway.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.bjpowernode.gateway.web.model.query.TradeReceiveQuery;
import org.springframework.stereotype.Component;

import java.util.TreeMap;

/**
 * 签名工具类
 */
@Component
public class SignUtil {


    /**
     * 验证签名  :  把接收的参数，重写按签名算法计算出新签名 和  originSign 比较
     *
     * @return
     */
    public boolean checkSignMsg(TradeReceiveQuery tradeReceiveQuery, String appSecret) {
        // 商家携带过来的签名
        String origonSign = tradeReceiveQuery.getSign();

        // 使用TreeMap 将 tradeReceiveQuery中的数据 按照字典序的顺序存入
        TreeMap<String, String> map = new TreeMap<>();
        map.put("userNo", tradeReceiveQuery.getUserNo());
        map.put("appKey", tradeReceiveQuery.getAppKey());
        map.put("payProductCode", tradeReceiveQuery.getPayProductCode());
        map.put("productId", tradeReceiveQuery.getProductId());
        map.put("productName", tradeReceiveQuery.getProductName());
        map.put("productNum", String.valueOf(tradeReceiveQuery.getProductNum()));
        map.put("payerId", tradeReceiveQuery.getPayerId());
        map.put("payerConcat", tradeReceiveQuery.getPayerConcat());
        map.put("orderMoney", String.valueOf(tradeReceiveQuery.getOrderMoney()));
        map.put("pageUrl", tradeReceiveQuery.getPageUrl());
        map.put("notifyUrl", tradeReceiveQuery.getNotifyUrl());
        map.put("orderNo", tradeReceiveQuery.getOrderNo());

        // 拼接出 签名数据格式  name=value&name=value
        StringBuilder stringBuilder = new StringBuilder();
        map.forEach((name , value) -> {
            if (StrUtil.isNotBlank(value)) {
                stringBuilder.append(name).append("=").append(value).append("&");
            }
        });
        stringBuilder.append("appSecret").append("=").append(appSecret);
        System.out.println("stringBuilder=" + stringBuilder.toString());

        // 将 数据进行md5加密 , 然后根商户传输过来的数据进行置比
        String md5Sign = DigestUtil.md5Hex(stringBuilder.toString());

        return md5Sign.equals(origonSign);
    }
}
